package com.playball.lottery.frm.hemai;

import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.playball.lottery.R;
import com.playball.lottery.ApplicationData;
import com.playball.lottery.customview.ShowCustomDialog;
import com.playball.lottery.customview.ShowTipDialog;
import com.playball.lottery.frm.yhzx.LoginActivity;
import com.playball.lottery.nt.GetRequestParams;
import com.playball.lottery.util.ConvertJsonToList;
import com.playball.lottery.util.LevelUtil;

/**
 * 合买大厅listview适配器
 * 
 * @author Administrator
 * 
 */
public class HemaiMainProcessListAdapter extends BaseAdapter {
	/** 运行上下文 */
	private Context context;
	/** 合买大厅listview数据 */
	private List<Map<String, Object>> mData;
	private LayoutInflater mInflater;
	// /** 全局变量 */
	// private ApplicationBall app;
	private int buy_icon;
	private int pos;
	/** 输入金额 */
	private float fEnter;
	private float fLeft;

	public HemaiMainProcessListAdapter(Context context, List<Map<String, Object>> appData) {
		this.context = context;
		mData = appData;
		this.mInflater = LayoutInflater.from(context);
		// 初始化数据
		for (int i = 0; i < appData.size(); i++) {
			appData.get(i).put("isCheck", 0);
			appData.get(i).put("ETValue", "");
		}

	}

	/**
	 * 当点击获取更多按钮时重新初始化购买框状态isCheck和输入框状态ETValue
	 * 
	 * @param data
	 */
	public void setData(List<Map<String, Object>> data) {
		// TODO Auto-generated method stub
		for (int i = 0; i < data.size(); i++) {
			data.get(i).put("isCheck", 0);
			data.get(i).put("ETValue", "");
		}
		this.mData = data;
	}

	@Override
	public int getCount() {
		// TODO Auto-generated method stub
		return mData.size();
	}

	@Override
	public Object getItem(int arg0) {
		// TODO Auto-generated method stub
		return mData.get(arg0);
	}

	@Override
	public long getItemId(int arg0) {
		// TODO Auto-generated method stub
		return arg0;
	}

	private Integer index = -1;

	public View getView(final int position, View convertView, final ViewGroup parent) {

		// System.out.println("getView " + position + " " + convertView);
		ViewHolder holder = null;
		if (convertView == null) {
			holder = new ViewHolder();
			convertView = mInflater.inflate(R.layout.hemai_main_process_singlelv, null);
			holder.ivMarkStar = (ImageView) convertView.findViewById(R.id.ivMarkStar);
			holder.bao_img = (ImageView) convertView.findViewById(R.id.bao_img);
			holder.rpProcess1 = (TextView) convertView.findViewById(R.id.rpProcess1);
			holder.tvPeople2 = (TextView) convertView.findViewById(R.id.tvPeople2);
			holder.tvLottery2 = (TextView) convertView.findViewById(R.id.tvLottery2);
			holder.tvLotMoney2 = (TextView) convertView.findViewById(R.id.tvLotMoney2);
			holder.tvLotMoney4 = (TextView) convertView.findViewById(R.id.tvLotMoney4);
			holder.tvYsq = (TextView) convertView.findViewById(R.id.tvYsq);
			holder.tvMerchandiserCount = (TextView) convertView.findViewById(R.id.tvMerchandiserCount);
			holder.llLeftInfo = (LinearLayout) convertView.findViewById(R.id.llLeftInfo);
			holder.llArrow = (LinearLayout) convertView.findViewById(R.id.llArrow);
			holder.llBelow = (LinearLayout) convertView.findViewById(R.id.llBelow);
			holder.ivArrow = (ImageView) convertView.findViewById(R.id.ivArrow);
			holder.etEnterMoney = (EditText) convertView.findViewById(R.id.etEnterMoney);
			holder.btnQuanbao = (Button) convertView.findViewById(R.id.btnQuanbao);
			// 将当前位置放入到tag中
			holder.etEnterMoney.setTag(position);
			// 设置输入框数据发生变化的监听事件
			holder.etEnterMoney.addTextChangedListener(new MyTextWatcher(holder) {
				private boolean isChanged = false;
				@Override
				public void afterTextChanged(Editable s, ViewHolder holder) {
					if (isChanged) {
						return;
					}
					int p = (Integer) holder.etEnterMoney.getTag();
					isChanged = true;
					int bs;
					if ("".equals(s.toString()))
						bs = 0;
					else
						bs = Integer.parseInt(s.toString());

					int rshare = Integer.parseInt(String.valueOf(mData.get(p).get("RShare")));

					String str2 = s.toString().trim().replaceFirst("^0*", "");
					if (bs < 1) {
						holder.etEnterMoney.setText("1");
						holder.etEnterMoney.selectAll();
						bs = 1;
					} else if (bs > rshare) {
						holder.etEnterMoney.setText(rshare + "");
						holder.etEnterMoney.selectAll();
						bs = rshare;
					} else {
						holder.etEnterMoney.setText(str2);
						holder.etEnterMoney.setSelection(holder.etEnterMoney.length());
					}

					modifyListNumber(bs + "", p);

					isChanged = false;
					// holder.etEnterMoney.invalidate();
				}

			});
			// 设置用户触摸输入框的监听事件
			holder.etEnterMoney.setOnTouchListener(new OnTouchListener() {
				@Override
				public boolean onTouch(View v, MotionEvent event) {
					if (event.getAction() == MotionEvent.ACTION_UP) {
						index = (Integer) v.getTag();
						// Log.e("index onTouch= ", index + "");
					}
					return false;
				}
			});

			holder.btnBuy = (Button) convertView.findViewById(R.id.btnBuy);

			convertView.setTag(holder);

		} else {

			holder = (ViewHolder) convertView.getTag();
			holder.etEnterMoney.setTag(position);
		}

		// 不同战绩图片
		int intPicId = Integer.parseInt(mData.get(position).get("Level").toString());
		if (LevelUtil.getLevelIcon(intPicId) == 0) {
			holder.ivMarkStar.setVisibility(View.INVISIBLE);
			// Log.i("intPicId0= ", intPicId+""+" position= "+position);
		} else {
			// Log.i("intPicId1= ", intPicId+""+" position= "+position);
			holder.ivMarkStar.setVisibility(View.VISIBLE);
			holder.ivMarkStar.setImageDrawable(context.getResources().getDrawable(LevelUtil.getLevelIcon(intPicId)));
		}
		// holder.tvProcess1.setText((String.valueOf(mData.get(position).get("Schedule")))
		// + "%");
		DecimalFormat df = new DecimalFormat("00");
		String schedule = df.format(Double.parseDouble(mData.get(position).get("Schedule").toString()));
		holder.rpProcess1.setText(schedule);
		// holder.rpProcess1.setProgress(Integer.parseInt(mData.get(position).get("Schedule").toString()));
		if ("100".equals(mData.get(position).get("Schedule").toString())) {
			holder.btnBuy.setEnabled(false);
			holder.btnBuy.setBackgroundResource(R.drawable.ui_new_btn_cancel_normal);
		} else {
			holder.btnBuy.setEnabled(true);
			holder.btnBuy.setBackgroundResource(R.drawable.ui_new_btn_yes_selector);
		}
		// 保底进度
		if ("0".equals(String.valueOf(mData.get(position).get("Assure")))) {
			// holder.tvProcess2.setText("-");
			holder.bao_img.setVisibility(View.GONE);
		} else {
			holder.bao_img.setVisibility(View.VISIBLE);
			// holder.tvProcess2.setText("保" +
			// String.valueOf(mData.get(position).get("Assure")) + "%");
		}
		// // 根据值判断颜色
		// String strpro1 =
		// (String.valueOf(mData.get(position).get("Schedule")));
		// String strpro2 = (String.valueOf(mData.get(position).get("Assure")));

		// if (HemaiDateUtil.StringToint(strpro1) +
		// HemaiDateUtil.StringToint(strpro2) >= 90) {
		// //
		// holder.tvProcess1.setTextColor(context.getResources().getColor(R.color.red));
		// holder.tvProcess1.setTextColor(Color.parseColor("#FE7A7A"));
		// } else {
		// //
		// holder.tvProcess1.setTextColor(context.getResources().getColor(R.color.orange));
		// holder.tvProcess1.setTextColor(context.getResources().getColor(R.color.common_content));
		// }
		// 预售期
		holder.tvPeople2.setText(String.valueOf(mData.get(position).get("UName")));
		if ("true".equals(String.valueOf(mData.get(position).get("IsYsq")))) {
			holder.tvYsq.setVisibility(View.VISIBLE);
		} else if ("false".equals(String.valueOf(mData.get(position).get("IsYsq")))) {
			holder.tvYsq.setVisibility(View.GONE);
		}

		if (String.valueOf(mData.get(position).get("LottName")).equals("超级大乐透")) {
			holder.tvLottery2.setText("大乐透");
		} else {
			holder.tvLottery2.setText(String.valueOf(mData.get(position).get("LottName")));
		}

		holder.tvLotMoney2.setText("¥" + String.valueOf(mData.get(position).get("Share")));
		holder.tvLotMoney4.setText("¥" + String.valueOf(mData.get(position).get("RShare")));

		if (mData.get(position).get("MerchandiserCount") != null) {
			holder.tvMerchandiserCount.setText(mData.get(position).get("MerchandiserCount").toString() + "人");
		}

		holder.etEnterMoney.setHint("剩余" + String.valueOf(mData.get(position).get("RShare")) + "");
		// 佣金比例
		// holder.tvCommission.setText(String.valueOf(mData.get(position).get("BScale"))+"%");

		if ((Integer) mData.get(position).get("isCheck") == 0) {
			holder.llBelow.setVisibility(View.GONE);
			holder.ivArrow.setBackgroundDrawable(context.getResources().getDrawable(R.drawable.hemai_down));
		} else {
			holder.llBelow.setVisibility(View.VISIBLE);
			holder.ivArrow.setBackgroundDrawable(context.getResources().getDrawable(R.drawable.hemai_up));
		}
		// Log.e("mData= ", mData.toString());
		// Log.e("isCheck= ", (Integer) mData.get(position).get("isCheck") +
		// "");

		// 改变值
		holder.llLeftInfo.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// 跳转到合买详情页面
				Intent intent = new Intent();
				intent.setClass(context, HeMaiDetailActivity.class);
				Bundle mBundle = new Bundle();
				mBundle.putString("SchemeID", String.valueOf(mData.get(position).get("SchemeID")));// 压入数据:方案ID
				mBundle.putString("UName", String.valueOf(mData.get(position).get("UName")));
				mBundle.putString("Level", String.valueOf(mData.get(position).get("Level")));
				mBundle.putString("Schedule", String.valueOf(mData.get(position).get("Schedule")));
				mBundle.putString("Assure", String.valueOf(mData.get(position).get("Assure")));
				//Log.d("van", mData.get(position).get("Assure")+"----------");
				mBundle.putString("LotName", String.valueOf(mData.get(position).get("LottName")));
				mBundle.putString("IsYsq", String.valueOf(mData.get(position).get("IsYsq")));
				mBundle.putString("Share", String.valueOf(mData.get(position).get("Share")));
				mBundle.putString("RShare", String.valueOf(mData.get(position).get("RShare")));
				mBundle.putString("BScale", String.valueOf(mData.get(position).get("BScale")));
				intent.putExtras(mBundle);
				context.startActivity(intent);
			}
		});

		holder.llArrow.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {

				// 显示购买,根据position
				// Log.e("position=", String.valueOf(position));

				if ((Integer) mData.get(position).get("isCheck") == 0) {
					mData.get(position).put("isCheck", 1);

				} else if ((Integer) mData.get(position).get("isCheck") == 1) {
					mData.get(position).put("isCheck", 0);
				}
				// Log.e("isCheck Listener= ", (Integer)
				// mData.get(position).get("isCheck") + "");
				// 重新调用getview，不要在此事件直接设置组件的显示
				notifyDataSetChanged();
			}
		});

		String strETValue = String.valueOf(mData.get(position).get("ETValue"));
		if (null != strETValue) {
			holder.etEnterMoney.setText(strETValue);
			holder.etEnterMoney.selectAll();
		}

		holder.btnQuanbao.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				int RShare = (Integer) mData.get(position).get("RShare");

				if (null != String.valueOf(RShare)) {
					// 存入数据
					mData.get(position).put("ETValue", String.valueOf(RShare));
				}

				notifyDataSetChanged();
			}
		});

		holder.btnBuy.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {

				if ("".equals(String.valueOf(mData.get(position).get("ETValue")))) {
					fEnter = 0;
				} else {
					fEnter = Float.parseFloat(String.valueOf(mData.get(position).get("ETValue")));
				}
				// Log.e("intEnter = ", intEnter + "");
				if (checkUserLogin()) {
					// 判断输入是否合法
					if (Math.abs(fEnter) < 0.0000001) { // 输入不能为0
						Toast.makeText(context, R.string.input_amount_can_not_be_empty, Toast.LENGTH_SHORT).show();
					} else if (fEnter > (Integer) mData.get(position).get("RShare")) {
						Toast.makeText(context, R.string.purchase_amount_cannot_exceed_subscription_amount,
								Toast.LENGTH_SHORT).show();
					} else {
						// 弹出购买提示框
						ShowCustomDialog/* AlertDialog.Builder */dialog = new ShowCustomDialog.Builder(context)
								.setTitle("购买提示").setMessage("是否确认购买？")

								.setPositiveButton("取消", new DialogInterface.OnClickListener() {
									@Override
									public void onClick(DialogInterface dialog, int which) {
										dialog.cancel();
									}
								}).setNegativeButton("确定", new DialogInterface.OnClickListener() {
									@Override
									public void onClick(DialogInterface dialog, int which) {
										pos = position;
										startHBuyThread(position);
										dialog.cancel();
									}
								}).createCustomDialog();
						dialog.setCanceledOnTouchOutside(false);
						dialog.setCancelable(true);// 设置back键是否可以取消
						dialog.show();

					}
				} else {
					Intent intent = new Intent(context, LoginActivity.class);
					context.startActivity(intent);
				}

			}
		});
		// 处理输入框焦点
		holder.etEnterMoney.clearFocus();
		if (index != -1 && index == position) {
			holder.etEnterMoney.requestFocus();
		}

		return convertView;
	}

	/**
	 * 购买金额输入框的数据设置
	 * 
	 * @param number
	 * @param p
	 */
	private void modifyListNumber(String number, int p) {
		if (p >= mData.size())
			return;
		mData.get(p).put("ETValue", number);
	}

	public static class ViewHolder {
		public ImageView ivMarkStar;
		public ImageView bao_img;
		// public TextView tvProcess1;
		public TextView rpProcess1;
		// public TextView tvProcess2;
		public TextView tvPeople2;
		public TextView tvLottery2;
		public TextView tvLotMoney2;
		public TextView tvLotMoney4;
		public ImageView ivArrow;
		// 佣金比例
		// public TextView tvCommission;
		// 是否预售期
		public TextView tvYsq;
		// 进度左侧信息线性布局
		public LinearLayout llLeftInfo;
		// 进度右侧箭头线性布局
		public LinearLayout llArrow;
		// 进度listview下方购买线性布局
		public LinearLayout llBelow;
		public EditText etEnterMoney;
		public Button btnBuy;
		public Button btnQuanbao;
		// 跟单人数
		public TextView tvMerchandiserCount;
	}

	/**
	 * 检测登录状态
	 * 
	 * @return
	 */
	public boolean checkUserLogin() {
		if (!ApplicationData.getInstance().getLoginName().equals("")
				&& !ApplicationData.getInstance().getLoginPwd().equals("")
				|| !ApplicationData.getInstance().getUserID().equals("")) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 购买请求
	 */
	private void startHBuyThread(int position) {
		AsyncLoader task = new AsyncLoader();
		String[] dyn = new String[2];
		JSONObject params = new JSONObject();

		try {
			// 设置请求所需参数
			params.put("BuyShare", fEnter);
			params.put("SchemeID", String.valueOf(mData.get(position).get("SchemeID")));
			params.put("DataSource", 1);// 数据来源 0老系统，1新系统
		} catch (JSONException ex) {
			// TODO Auto-generated catch block
			Log.e("error", ex.toString());
		}
		dyn[0] = params.toString();
		// dyn[1] = "213";
		// 参与合买
		dyn[1] = "209";
		// Log.e("startHBuyThread= ", dyn[1].toString() + " " +
		// dyn[0].toString());
		task.execute(dyn);
	}

	/**
	 * 异步发送接收处理网络数据
	 * 
	 * @author Administrator
	 * 
	 */
	class AsyncLoader extends AsyncTask<String, Integer, String> {// 继承AsyncTask

		String action;
		ShowTipDialog showdialog = new ShowTipDialog();

		// 1.准备运行
		protected void onPreExecute() {
			showdialog.showDialog(context);
		}

		// 2.正在后台运行
		@Override
		protected String doInBackground(String... paramsArr) {
			// 处理后台执行的任务，在后台线程执行
			String strResult = null;

			action = paramsArr[1];
			// 获取请求返回值
			// strResult = GetRequestParams.getRequestResult(paramsArr[0],
			// action, context.getApplicationContext());
			String UserID = ApplicationData.getInstance().getUserID();
			strResult = GetRequestParams.getRequestUserIDResult(paramsArr[0], UserID, action,
					context.getApplicationContext());
			// 获取请求返回值
			return strResult;
		}

		// 3.进度更新
		protected void onProgressUpdate(Integer... progress) {
		}

		// 4.完成后台任务
		protected void onPostExecute(String result) {
			if (result != null) {

				if (action.equals("209")) {
					// 购买
					HdetailBuy(result);
				}
				showdialog.closeDialog();
			} else {
				Toast.makeText(context, context.getString(R.string.problem_01), Toast.LENGTH_LONG).show();
			}
		}

		// 5.完成后操作
		protected void onCancelled() {
		}

	}

	/**
	 * 购买完成结束弹出对话框
	 * 
	 * @param strResult
	 */
	public void HdetailBuy(String strResult) {
		try {
			JSONTokener jsonParser = new JSONTokener(strResult);
			JSONObject js = (JSONObject) jsonParser.nextValue();
			// Log.i("strResult= ", strResult);
			if (Integer.parseInt(js.getString("Code")) < 0) {
				buy_icon = R.drawable.buy_failure;
				// Log.i("Message= ", js.getString("Message"));
				// 余额不足
				if ("余额不足".equals(js.getString("Data"))) {
					// new ShowTipDialog().showHBuyInfo(context,
					// js.getString("Data"), "购买失败", buy_icon);
					new ShowTipDialog().showHBuyInfo(context, "您的当前余额不足，请先充值，再购买投注。", "购买失败", buy_icon);
				} else if ("方案已被用户撤单".equals(js.getString("Data"))) {
					new ShowTipDialog().showHBuyInfo(context, js.getString("Data"), "温馨提示", buy_icon);
				} else if (js.getString("Data").startsWith("方案剩余")) {
					// msg="方案剩余份数已不足 1893 份,剩余 1891 份";//新 彩豆{ "Code": -1,
					// "Data": "方案剩余金额已不足2彩豆,剩余1彩豆"}
					String[] arr = js.getString("Data").split(",");
					String a = arr[1];
					String s = a.substring((a.indexOf("余") + 1), a.indexOf("彩豆"));
					fLeft = Float.parseFloat(s.trim());
					ShowCustomDialog.Builder alertbBuilder = new ShowCustomDialog.Builder(context);
					alertbBuilder.setTitle("购买失败");
					// alertbBuilder.setMessage("可认购金额已不足"+fEnter+"彩豆，当前剩余金额为"+fLeft+"彩豆，是否确定购买？");
					alertbBuilder.setMessage("该方案已满员");
					// alertbBuilder.setIcon(buy_icon);

					alertbBuilder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							// 以剩余金额继续购买
							fEnter = fLeft;
							// startHBuyThread(pos);
							// Log.i("intEnter= ", intEnter + "");
							dialog.cancel();
						}
					}).createCustomDialog().show();
					/*
					 * Dialog dialog = alertbBuilder.create();
					 * dialog.setCanceledOnTouchOutside(false);
					 * dialog.setCancelable(false);// 设置back键是否可以取消
					 * dialog.show();
					 */

				} else {
					new ShowTipDialog().showHBuyInfo(context, js.getString("Data"), "购买失败", buy_icon);
				}

			} else {
				buy_icon = R.drawable.buy_success;

				// String msg = "发起合买" +
				// mData.get(pos).get("EndTime").toString() + "期购买方案\n\n方案金额：" +
				// mData.get(pos).get("Share").toString() + "彩豆\n我的认购：" + fEnter
				// + "彩豆";//\n账户余额：" + getBalance() + "彩豆
				String msg = "参与" + mData.get(pos).get("UName").toString() + "发起合买方案\n\n方案金额："
						+ mData.get(pos).get("Share").toString() + "彩豆\n我的认购：" + fEnter + "彩豆";// \n账户余额：" + getBalance() + "彩豆
				// Log.i("msg= ", "购买 " + msg);
				new ShowTipDialog().showHBuyInfo(context, msg, js.getString("Data"), buy_icon);
			}
		} catch (JSONException e) {
			// 异常处理代码
			Log.e("error", e.toString());
		}
	}

	/**
	 * 获取账户余额
	 * 
	 * @return
	 */
	public String getBalance() {
		String money = "";
		String strResult = null;
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			// 设置请求所需参数
			JSONObject params = new JSONObject();
			// 设置请求action
			String action = "107";// 108获取用户基本信息
			// 获取请求返回值
			String UserID = ApplicationData.getInstance().getUserID();
			strResult = GetRequestParams.getRequestUserIDResult(params.toString(), UserID, action, context);
			JSONTokener jsonParser = new JSONTokener(strResult);
			JSONObject js = (JSONObject) jsonParser.nextValue();
			map = ConvertJsonToList.getMap(js.getString("Data"));
			// money =
			// Float.parseFloat(map.get("Balance").toString().replaceAll(",",
			// "").trim());
			money = map.get("Balance").toString();
		} catch (Exception ex) {
			// TODO Auto-generated catch block
			Log.e("error", ex.toString());
		}
		return money;
	}

	/**
	 * 自定义TextWatcher
	 * 
	 * @author Administrator
	 * 
	 */
	private abstract class MyTextWatcher implements TextWatcher {
		private ViewHolder mViewHolder;

		public MyTextWatcher(ViewHolder holder) {
			mViewHolder = holder;
		}

		@Override
		public void afterTextChanged(Editable s) {
			afterTextChanged(s, mViewHolder);
		}

		@Override
		public void beforeTextChanged(CharSequence s, int start, int count, int after) {

		}

		@Override
		public void onTextChanged(CharSequence s, int start, int before, int count) {

		}

		public abstract void afterTextChanged(Editable s, ViewHolder holder);

	}

}
